/*
 *      You may freely copy, distribute and reuse the code
 *      in this example.  Scott Anguish disclaims any warranty of
 *      any kind, expressed or implied, as to its fitness
 *      for any particular use.
 *		Please keep this notice intact
 *      Written by: Scott Anguish  sanguish@digifix.com
 */

#import "MMText.h"

#import <libc.h>					  /* MAXPATHLEN */
#import <stdio.h>
#import <strings.h>

#import <appkit/appkit.h>

#import <streams/streams.h>


@implementation MMText:Text

+ initialize
{
	[super initialize];
	[Text registerDirective:"NGFolder" forClass: [MMFolderCell class]];
	[Text registerDirective:"NGGraphic" forClass: [MMGraphicCell class]];
	[Text registerDirective:"NGDocument" forClass: [MMDocumentCell class]];
	return self;
}

- (BOOL)isHeaderVisible:(const char*)header
{
	if ((strncmp(header,"From:",5)==0) 			&& showFrom)  return YES;
	if ((strncmp(header,"Date:",5)==0) 			&& showDate)  return YES;
	if ((strncmp(header,"Newsgroups:",11)==0)	&& showNewsgroups)  return YES;
	if ((strncmp(header,"Subject:",8)==0)		&& showSubject)  return YES;
	if ((strncmp(header,"MessageID:",10)==0)	&& showMessageID)  return YES;
	if ((strncmp(header,"Path:",5)==0)			&& showPath)  return YES;
	if ((strncmp(header,"Followup-To:",12)==0)	&& showFollowupTo)  return YES;
	if ((strncmp(header,"Expires:",8)==0)		&& showExpires)  return YES;
	if ((strncmp(header,"Reply-To:",9)==0)		&& showReplyTo)  return YES;
	if ((strncmp(header,"Sender:",7)==0)		&& showSender)  return YES;
	if ((strncmp(header,"Control:",8)==0)		&& showControl)  return YES;
	if ((strncmp(header,"Keywords:",9)==0)		&& showKeywords)  return YES;
	if ((strncmp(header,"Summary:",8)==0)		&& showSummary)  return YES;
	if ((strncmp(header,"Approved:",9)==0)		&& showApproved)  return YES;
	if ((strncmp(header,"Lines:",6)==0)			&& showLines)  return YES;
	if ((strncmp(header,"Xref:",5)==0)			&& showXref)  return YES;
	if ((strncmp(header,"Organization:",13)==0)	&& showOrganization)  return YES;

	return NO;
}

- setVisibleHeaders
{
	showFrom=YES;
	showDate=YES;
	showNewsgroups=NO;
	showSubject=YES;
	showMessageID=NO;
	showPath=NO;
	showFollowupTo=NO;
	showExpires=NO;
	showReplyTo=NO;
	showSender=NO;
	showReferences=NO;
	showControl=NO;
	showDistribution=NO;
	showKeywords=NO;
	showSummary=NO;
	showApproved=NO;
	showLines=NO;
	showXref=NO;
	showOrganization=NO;


	return self;

};
- initFrame:(const NXRect *)frameRect
{
	self = [super initFrame:frameRect];
	[self notifyAncestorWhenFrameChanged:YES];
	[self setMonoFont:NO];
	[self setVertResizable:YES];
	[self setHorizResizable:NO];
	[self setSel:0:0];
	[self setOpaque:YES];

	{ NXSize aSize = {1.0E38,1.0E38};
	  [self setMinSize:&frameRect->size];
	  [self setMaxSize:&aSize];
  }
	[self setVisibleHeaders];
	return self;
}

- free
{	

	[super free];
	return self; 
}

- (int)iconEntered:(int)windowNum at:(double)x :(double)y
    iconWindow:(int)iconWindowNum iconX:(double)iconX iconY:(double)iconY
    iconWidth:(double)iconWidth iconHeight:(double)iconHeight
    pathList:(char *)pathList
{


    if (!iconPathList || strcmp(iconPathList, pathList)) 
		{
		if (iconPathList) NX_FREE(iconPathList);
		NX_MALLOC(iconPathList,char, strlen(pathList)+1);
		//iconPathList = NXCopyStringBufferFromZone(pathList, [self zone]);
		strcpy(iconPathList, pathList);
		}
    return 0;
}

- (int)iconReleasedAt:(double)x :(double)y ok:(int *)flag
{
	if (![self isEditable]) 
		{
    	*flag = NO;
		} else 
		{
		*flag = YES;
		[self perform:@selector(delayIconReleasedAt:) with:self afterDelay:5 cancelPrevious:YES];
		}
	return 0;
}

- delayIconReleasedAt:sender
{
    int dummy,*flag;
    
    NXPoint p;
    char *file,  *tab, *extension;
    id	newCell;
    int foundOne ;

    flag = &dummy;
    
    foundOne = NO;

    [window convertScreenToBase:&p];
    [self convertPoint:&p fromView:nil];


    
	file = iconPathList;
	while (file) {
	    tab = strchr(file, '\t');
	    if (tab) *tab = '\0';
	    extension = strrchr(file, '.');
	    if (extension &&
		( !strcmp(extension, ".ps")  || !strcmp(extension, ".eps") ||
		  !strcmp(extension,".tiff") || !strcmp(extension,".tif")  )) {
		    
		    newCell =[[MMGraphicCell alloc] imageFromFilename:file];
		    [self replaceSelWithCell:newCell];
		    foundOne = YES;
		    
	    } else {
		    newCell = [[MMDocumentCell alloc] imageFromFilename:file];
		    [self replaceSelWithCell:newCell];
		    foundOne = YES;
	    }
	    	
	   file = tab ? ++tab : NULL;
	}
    
    *flag = foundOne;
    return 0;
}

 
- becomeFirstResponder
{
	[super becomeFirstResponder];
	return self;
}

- appendBoldWord:(char *)aString
{
	int length;
	char header[BUFSIZ],restofline[BUFSIZ];

	sscanf(aString,"%s%[^\n]", header,restofline);
	strcat(restofline,"\n");
	
	if ([self isHeaderVisible:header])
		{
		length = [self textLength];
		[self setSel:length:length];
		[self replaceSel:header];
		[self setSel:(length):[self textLength]];
		[self setSelFont:[Font newFont:"Courier-Bold" size:12.0]];
	
		length = [self textLength];
		[self setSel:length:length];
		[self replaceSel:restofline];
		[self setSel:(length):[self textLength]];
		[self setSelFont:[Font newFont:"Courier" size:12.0]];
	
		length = [self textLength];
		[self setSel:length:length];
		};
	return self;

};

- appendRichFile:(char *)aFile
{
	NXStream *aStream;
	int length;

	length = [self textLength];
	[self setSel:length:length];
	aStream=NXMapFile(aFile,NX_READONLY);
	[self replaceSelWithRichText:aStream];
	NXClose(aStream);
	return self;
};

- openFileName:(char *)aFile
{
	[self openFileName:aFile ignoreHeader:NO];
	return self;
}

- openFileName:(char *)aFile ignoreHeader:(BOOL)ignoreHeader
{

    FILE	*filePtr,*outfile;
	char 	theLine[BUFSIZ];
	BOOL 	NGfound;
	
	[self setText:""];
	NGfound=NO;
	
	[[self window] disableFlushWindow];
	[self setEditable:NO];
    filePtr = fopen(aFile, "r");
	if (ignoreHeader)
		{
		while (fgets(theLine,BUFSIZ, filePtr) != NULL)
			{
				if (strncmp(theLine, "\n",1)==0)
					{
						break;
					};
				[self appendBoldWord:theLine];
			};

		[self replaceSel:"\n\n"];
		}
	while (fgets(theLine,BUFSIZ, filePtr) != NULL)
		{
			
			if (strncmp(theLine, NGHEADER,strlen(NGHEADER))==0)
				{
					NGfound=YES;
					break;
				};
		};
	if (NGfound)
		{

		if (outfile = popen("rm /tmp/NGtemp; /usr/bin/uudecode ","w"))
			{
			fprintf(outfile,"begin 644 /tmp/NGtemp\n");
			while (fgets(theLine,BUFSIZ, filePtr) != NULL) 
				{if (strncmp(theLine,"`",1)==0) 
					{
						fprintf(outfile,"`\n");
						break;
					}
					else
					fputs(theLine,outfile);
				};
			fprintf(outfile,"end\n");
			if (pclose(outfile)==0) [self appendRichFile:"/tmp/NGtemp"];
				else NXRunAlertPanel("NGService","Unable to decode! Check selection.",
		   NULL, NULL, NULL);
			(void)remove("/tmp/NGtemp");
			};

		};
	if (!NGfound) NXRunAlertPanel("NGService","I could not find any NewsGrazer Data!",
		   NULL, NULL, NULL);
    fclose(filePtr);
	[self sizeToFit];
    [[[self window] reenableFlushWindow] flushWindow];
	[self display];
	return self;

}

- readFromMemory:(char *)data length:(int)theSize
{

	NXStream *aStream;
	char filename[MAXPATHLEN+1];
	
	[self setText:""];
	
	strcpy(filename,"/tmp/file000000Selection" );
	NXGetTempFilename(filename,9);
	aStream = NXOpenMemory(data, theSize ,NX_READONLY);
	NXSaveToFile(aStream, filename);
	NXCloseMemory(aStream,NX_FREEBUFFER);
	[self openFileName:filename];
	(void)remove(filename);
	return self;

}


- saveFileName:(char *)aFile
{
	NXStream *aStream;

	aStream = NXOpenMemory(NULL,0, NX_WRITEONLY);
	
	[self writeRichText:aStream];
	
	NXSaveToFile(aStream, aFile);
	NXCloseMemory(aStream, NX_FREEBUFFER);
	
	return self;
}



@end
